<template>
	<view class="duty_clock_box">
		<Tips/>
		<view class="header">
			<view class="orther_info" style="z-index: 3;">
				<view class="item" @click="clickFillCardCount">
					<view style="z-index: 2;">
						<MyIcons size="55rpx" :src="joinSystemPath('cardCount.png')"/>
					</view>
					<view class="count">
						补签卡：{{changeNums(dutyInfo.fillClockCount,100)}}
					</view>
				</view>
				<view class="item" @click="()=>modalClockRule = Math.random()">
					打卡规则
				</view>
			</view>
			<view class="duty_info_box">
				<view class="user" v-if="dutyInfo?.id">
					<Avatar :fileName="dutyInfo.user.user_avatar" size="70rpx" />
					<view class="name text_ellipsis">{{dutyInfo.user.nick_name_by_dormitory}}</view>
				</view>
			</view>
			<view class="duty_info">
				每月的
				<view class="week">{{changeWeekByNum(dutyInfo.week)}}</view>
				值日
			</view>
			<view class="duty_clock_count">
				本月:
				打卡<view class="yes count">{{clockCount.firstAndFill}}</view>次
				缺卡<view class="no count">{{clockCount.lose}}</view>次
			</view>
			<view class="duty_clock_count_2">
				该值日为<view class="count">{{dutyWeekType===WeekType.SIGLE ? '单周' : '双周'}}</view>值日 
				| 
				本周为<view class="count">{{dormitoryWeekType===WeekType.SIGLE ? '单周' : '双周'}}</view>
			</view>
			<image
				style="width: 388rpx; height: 300rpx;position: absolute;right: -20rpx;top:20rpx" 
				mode="aspectFit"
				:src="joinSystemPath('dutyClock.png')"/>
		</view>
		<view class="content">
			<view class="duty_calendar">
				<DuckClock 
					@toggleDate="toggleDateFun" 
					@clickDateByChild="clickDateByChildFun"
					@clockDataEmit="getClockDateFun"
					:data="clockData"
					:targetYear="Number(targetYear)"
					:targetMonth="Number(targetMonth)"
					:dutyWeek="Number(dutyInfo.week)"
					:dutyInfo="dutyInfo"
				/>
				<view class="duty_clock_btn_box" v-if="isSelf">
					<MyButton 
						borderRadius="50rpx"
						:bgc="primary_light_color"
						:clickFun="clickClockBtnFun"
					>
						{{btnTextArr[dutyClockForm.info].text}}
					</MyButton>
				</view>
			</view>
			<MyCard>
				<view @click="clickEditClock" class="edit" v-if="isSelf && [1,2].indexOf(dutyClockForm.info)!==-1">
					<MyIcons size="40rpx" :src="joinSystemPath('editor.png')"/>编辑
				</view>
				<view class="clock_info_item" :style="targetClockData.img ? 'margin-top: 10rpx' : ''">
					<view class="title">
						<MyIcons size="40rpx" :src="joinSystemPath(btnTextArr[dutyClockForm.info].icon)"/>
					</view>
					&nbsp;{{btnTextArr[dutyClockForm.info].status}}
				</view>
				<view class="clock_info_item_info" :style="targetClockData.img ? 'margin-top: 10rpx' : ''">
					<view class="title">
						<MyIcons size="40rpx" :src="joinSystemPath('clockInfo.png')"/>
					</view>
					&nbsp;
					<view class="info">
						{{targetClockData.info}}
					</view>
				</view>
				<view class="clock_info_item_info" :style="targetClockData.img ? `margin-top: 10rpx;margin-bottom:${targetClockData.img === 'nullClock.jpg' ? '' : '20rpx'}` : ''">
					<view class="title">
						<MyIcons size="40rpx" :src="joinSystemPath('clockImg.png')"/>
					</view>&nbsp;
					<view class="info imgs">
						<Avatar v-for="item in targetClockData.img?.split(',')" :key="item" :isAllowPreview="true" radius="0rpx" :size="item ? '180rpx' : '0rpx'" :fileName="item" :joinUrlFun="joinDutyClockImg"/>
					</view>
				</view>
			</MyCard>
		</view>
			<!-- :height="noBindPhone ? '340rpx' : '220rpx'" -->
		<MyPopub 
			:height="'340rpx'" 
			:isOpenPopub="openPopubFlag" 
			:slotsNums="3"
		>
			<template #1>
				<view class="pupub_item" @click="goBindPhone">
					观看15秒广告获取补签卡
				</view>
			</template>
			<template #2>
				<view class="pupub_item" @click="goInviteFun">
					邀请助力得补签卡
				</view>
			</template>
			<template #3>
				<view class="pupub_item" @click="goHelpList">
					收到得助力
				</view>
			</template>
		</MyPopub>
		<MyModal :openModalFlag="modalClockRule" :okFun="()=>()=>modalClockRule = -Math.random()">
			<template #title>
				打卡规则
			</template>
			<template #content>
				<TipInfo :color="shallow_text_color" id="5"></TipInfo>
			</template>
		</MyModal>
		
		<MyModal :openModalFlag="isGoUserPageModel" :okFun="getUserPage">
			<template #title>
				获取短信通知次数
			</template>
			<template #content>
				<view :style="`color:${primary_text_color}`">
					您的短信通知次数不足了(需满足>=2)，是否去免费获取次数？
				</view>
				<view :style="`color:${shallow_text_color};font-size:26rpx;`">
					次数扣除时间：每天凌晨3点扣除昨天用掉的次数
				</view>
			</template>
		</MyModal>
		<MyModal :openModalFlag="modalEditClock" :okFun="submitEditDutyClock">
			<template #title>
				编辑打卡内容
			</template>
			<template #content>
				<uni-easyinput
					:primaryColor="primary_cool_color" 
					type="textarea"
					:autoHeight="true"
					v-model="editClockContentForm.info" 
					placeholder="请输入备注"
				/>
				<view class="upload_tip">
					上传宿舍图片（支持多张）
				</view>
				<view class="proof">
					<view class="img" @click="uploadImg" style="background-color: rgba(0, 0, 0, 0.05);;width:150rpx;height:150rpx;">
						<Avatar
							size="100rpx"
							:isAllowPreview="false"
							radius="10rpx"
							fileName="addImg.png" 
							:joinUrlFun="joinVoteImg"/>
					</view>
					<template v-for="item in imgArr" :key="item">
						<view class="img" v-if="item!==''" :key="item">
							<view
								class="close_btn"
								@click.stop="deleteImg(item)"
							>
								<MyIcons size="30rpx" :src="joinSystemPath('closeRed2.png')"/>
							</view>
							<Avatar :isAllowPreview="true" radius="0rpx" :size="imgSize" :fileName="item" :joinUrlFun="joinDutyClockImg"/>
						</view>				
					</template>
				</view>
			</template>
		</MyModal>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		computed,
		ref, 
		watchEffect,
		watch,
		nextTick
	} from 'vue'
	
	import moment from 'moment'
	
	import {
		dynamicStyleStore
	} from '@/stores/dynamicStyle.js'
	import {
		userStore
	} from '@/stores/user'
	
	import {
		DormitoryModel
	} from '@/service/model/dormitory.js'
	
	import {
		WeekType
	} from '../../../enum/GlobalEnum'
	
	import {
		joinSystemPath,
		joinDutyClockImg,
		joinVoteImg
	} from '@/utils/imgJoinName.js'
	import {
		changeWeekByNum,
		changeNums
	} from '@/utils/changeData.js'
	import {
		openMessageAuth
	} from '@/utils/messageAuth.js'
	import {
		verifyIsLogin,
		verifyFormData,
		MessageAndBindPhone,
		verifyIsShowChooseAd
	} from '@/hooks/verify.js'
	import {uploadImgHook} from '@/hooks/uploadImg.js'
	
	import Avatar from '@/components/Avatar/Avatar.vue'
	import DuckClock from '@/components/Dormitory/DutyClock/DutyClock.vue'
	import MyCard from '@/components/MyCard/MyCard.vue'
	import MyButton from '@/components/MyButton/MyButton.vue'
	import Tips from '@/components/Tips/Tips.vue'
	import MyIcons from '@/components/MyIcons/MyIcons.vue'
	import MyPopub from '@/components/MyPopub/MyPopub.vue'
	import TipInfo from '@/components/TipInfo/TipInfo.vue'
	import MyModal from '@/components/MyModal/MyModal.vue'
	
	import { DutyClockState,DefaultPhone } from '../../../enum/GlobalEnum'
	
	const dynamicStyle_store = dynamicStyleStore()
	const user_store = userStore()
	const dormitoryModel = new DormitoryModel()
	const isSelf = computed(()=>user_store.userInfo?.id === dutyInfo.value.user?.user_id)
	const noBindPhone = computed(()=>user_store.userInfo.phone === DefaultPhone)
	const clockCount=ref({firstAndFill:0,lose:0})
	const {
		primary_light_color,
		primary_text_color,
		primary_text_hot_color,
		primary_count1_color,
		success,
		primary_success,
		primary_cool_color,
		shallow_text_color
	} = dynamicStyle_store.dormitoryStyle
	
	const dutyInfo = ref({fillClockCount:0})
	const dutyId = ref('')
	
	const targetYear=ref(moment().format("YYYY"))
	const targetMonth=ref(moment().format("M"))
	const clockData = ref({})
	const isGoUserPageModel=ref(0)
	const modalEditClock = ref(-Math.random())
	const modalClockRule =ref(-Math.random())
	const openPopubFlag=ref(-Math.random())
	const dutyClockForm=ref({
		date:moment().format("YYYY-MM-DD"),
		info:(moment().weekday() || 7) === Number(dutyInfo.value.week) ? DutyClockState.GONING : 4
	})
	const dutyWeekType = ref(0)
	const dormitoryWeekType = ref(0)
	const editClockContentForm=ref({info:"",img:"",clockDay:moment().format("YYYY-MM-DD")})
	const imgArr = computed(()=>editClockContentForm.value.img?.split(',') || [])
	const btnTextArr=[
		{
			text:"立即补卡",
			status:"缺卡",
			icon:"loseClock.png",
			disabled:false
		},
		{
			text:"已打卡",
			status:"已打卡",
			icon:"firstClock.png",
			disabled:true
		},
		{
			text:"已补卡",
			status:"已补卡",
			icon:"fillClock.png",
			disabled:true
		},
		{
			text:"现在打卡",
			status:"今天还未打卡",
			icon:"goingClock.png",
			disabled:false
		},
		{
			text:"该天不是您值日",
			status:"该天不是您值日",
			icon:"noNeedClock.png",
			disabled:true
		},
		{
			text:"该天的值日是暂停的",
			status:"该天的值日是暂停的",
			icon:"noNeedClock.png",
			disabled:true
		}
	]
	
	const targetClockData=ref({info:null,img:null,clockType:null,clockDay:moment().format("YYYY-MM-DD")})
	const imgSize=ref(0)
	const alignInfo=ref('')
	watch(()=>editClockContentForm.value.img,()=>{
		if(editClockContentForm.value.img.length>1){
			imgSize.value = '150rpx'
			alignInfo.value='center'
		}else{
			imgSize.value = '0rpx'
			alignInfo.value=''
		}
	},{immediate:true})
	watchEffect(()=>{
		const clockList = clockData.value?.clockList || []
		for(let i=0;i<clockList.length;i++){
			const _date = moment(clockList[i].clockTime).utcOffset(8).format("YYYY-MM-DD")
				if(_date===dutyClockForm.value.date && !dutyClockForm.value.isToggleLR){
					let {info,img,clockType} = clockList[i]
					targetClockData.value={
						info,
						img,
						clockType,
						clockDay:_date
					}
					break
				}else{
					targetClockData.value={
						info:"没有信息",
						img:"nullClock.jpg",
						clockType:0,
						clockDay:_date
					}
				}
		}
	})
	
	const editDutyClockSchema={
		info:{
			required:true,
			tip:'备注'
		}
	}
	const submitEditDutyClock=async()=>{
		verifyIsLogin()
		verifyFormData(editClockContentForm.value,editDutyClockSchema)
		verifyIsShowChooseAd(getCurrentPages(),'编辑打卡')
		const _data=editClockContentForm.value
		_data.week = moment(_data.clockDay).weekday() || 7
		_data.clockType = targetClockData.value.clockType
		const {data,success} = await dormitoryModel.patchDutyClock(_data,dutyId.value)
		if(success){
			init()
			getDutyClockListFun()
			modalEditClock.value = -Math.random()
			uni.$emit('tips',data,'success')
			MessageAndBindPhone()
		}
	}
	
	const clickEditClock=()=>{
		const {info,img,clockDay} = targetClockData.value
		editClockContentForm.value={info,img,clockDay}
		const callback = ()=>{
			modalEditClock.value = Math.random()
		}
		uni.$emit('checkUserPrivacyProtocol',callback)
	}
	
	const clickFillCardCount=()=>{
		if(!isSelf.value){
			uni.$emit('tips','不能操作别人的补签卡','warn')
			return
		}
		openPopubFlag.value = Math.random()
	}
	
	const goBindPhone=()=>{
		const bindPhoneSuccess=async()=>{
			openPopubFlag.value = -Math.random()
			const {data,success} = await dormitoryModel.postAddDutyClockFillCount({},dutyId.value)
			if(success){
				setTimeout(()=>{
					uni.$emit('tips',data,'success')
					getDuytInfoFun(false)
				},1000)
			}
		}
		uni.$emit('viewVideoGoTask',bindPhoneSuccess)
	}
	
	const goInviteFun=()=>{
		openPopubFlag.value = -Math.random()
		uni.navigateTo({
			url:`/pages/Dormitory/InviteHelp/InviteHelp?duty_id=${dutyId.value}&share=true&type=duty_clock_fill_help`
		})
	}
	const goHelpList=()=>{
		openPopubFlag.value = -Math.random()
		uni.navigateTo({
			url:`/pages/Dormitory/helpRecord/helpRecord?type=duty_clock_fill_help&duty_id=${dutyId.value}`
		})
	}
	
	const clickDateByChildFun=(v,isDay=false)=>{
		console.log('点击率',v)
		if(!v?.date){
			v={
				date:null,
				info:4,
				isToggleLR:true
			}
			if(isDay) delete v.isToggleLR
		}else if(v.date === moment().format('YYYY-MM-DD') && dutyWeekType.value!==dormitoryWeekType.value){
			//今天的周类型与宿舍的周类型不同，故也也不轮到值日
			v.info = 4
		}
		dutyClockForm.value=v
	}
	
	const init=()=>{
		clockData.value = {}
	}
	
	const clickClockBtnFun=async()=>{
		const {date:clockDay,info} = dutyClockForm.value
		if(!clockDay) return
		const week = moment(clockDay).weekday() || 7
		verifyIsShowChooseAd(getCurrentPages(),'打卡')
		if(info===DutyClockState.GONING){
			const {data,success} = await dormitoryModel.postDutyClock({
				clockDay,
				week,
				dutyWeekType:dutyWeekType.value
			},dutyId.value)
			if(success){
				init()
				getDuytInfoFun()
				getDutyClockListFun()
				uni.$emit('tips',data,'success')
				
				MessageAndBindPhone()
				if(user_store.userInfo?.shortPushCount<=1 && user_store.userInfo?.phone !== '15888888888'){
					isGoUserPageModel.value = Math.random()
				}
			}
		}else if(info === DutyClockState.LOSE){
			const {data,success} = await dormitoryModel.postDutyClockFill({
				clockDay,
				week,
				dutyWeekType:dutyWeekType.value
			},dutyId.value)
			if(success){
				init()
				getDutyClockListFun()
				dutyClockForm.value.info = DutyClockState.FULL
				uni.$emit('tips',data,'success')
				dutyInfo.value.fillClockCount --
				MessageAndBindPhone()
				if(user_store.userInfo?.shortPushCount<=1 && user_store.userInfo?.phone !== '15888888888'){
					isGoUserPageModel.value = Math.random()
				}
			}else{
				if(data.status === 400){
					openPopubFlag.value = Math.random()
				}
			}
		}
	}
	
	//去个人页面
	const getUserPage=()=>{
		uni.switchTab({
			url:'/pages/User/User'
		})
	}
		
	const getDuytInfoFun=async(flag=true)=>{
		const {data,success} = await dormitoryModel.getDutyInfo({},dutyId.value)
		if(success){
			dutyInfo.value = data
			const {duty_weekType,dormitory_weekType} = data
			dutyWeekType.value = duty_weekType
			dormitoryWeekType.value = dormitory_weekType
			if(flag){
				dutyClockForm.value.info = 
				(moment().weekday() || 7) === Number(data.week) && (duty_weekType === dormitory_weekType)
					? (data.clocked === dutyClockForm.value.date && data.clocked!==null
						? DutyClockState.FIRST : DutyClockState.GONING) : 4
			}
		}
	}
	
	//从日历组件拿到打卡统计
	const getClockDateFun=(clockList)=>{
		clockList = clockList || []
		let firstAndFill=0,lose=0
		clockList.forEach(item=>{
			if([1,2].indexOf(item.info)!==-1){
				firstAndFill++
			}else if(item.info === 0){
				console.log('信息',item)
				lose++
			}
		})
		clockCount.value = {
			firstAndFill,
			lose
		}
	}
	
	const getDutyClockListFun=async()=>{
		let {data,success}=await dormitoryModel.getDutyClockList({
			year:targetYear.value,
			month:targetMonth.value
		},dutyId.value)
		if(success){
			clockData.value = {...data}
		}
	}
	
	//打卡图片上传
	const uploadImg=()=>{
		verifyIsLogin()
		uploadImgHook("uploadDutyClockImg",`/upload/duty/clock`)
	}
	
	const deleteImg=(item)=>{
		const arr = editClockContentForm.value.img?.split(',') || []
		const index = arr.findIndex(i=>i===item)
		if(index!==-1){
			arr.splice(index,1)
		}
		editClockContentForm.value.img=arr.join(',')
	}
	
	//监听图片上传成功
	uni.$on('uploadDutyClockImg',function(data){
		;(()=>{
			if(data){
				if(!editClockContentForm.value.img){
					editClockContentForm.value.img = data
				}else{
					editClockContentForm.value.img = editClockContentForm.value.img+','+data
				}
			}
		})()
	})
	
	//切换日期
	const toggleDateFun=(v)=>{
		const {year,month,isDay} = v.valueYM
		const extraInfo = v.extraInfo
		clockData.value = {}
		targetYear.value = year
		targetMonth.value = month
		getDutyClockListFun()
		// 处理当前选中天数在切换月份的问题
		const date = extraInfo?.date
		if(date && moment(`${year}-${month}`).format("YYYY-MM")===moment(date).format("YYYY-MM")){
			clickDateByChildFun(extraInfo)
		}else{
			const _year = Number(moment(date).format('YYYY'))
			const _month = Number(moment(date).format('MM'))
			clickDateByChildFun(null,isDay)
			if(_year !== year || _month !== month){
				targetClockData.value.info="没有信息"
				targetClockData.value.img = "nullClock.jpg"
			}
		}
		if(isDay){
			dutyClockForm.value.date = moment().format("YYYY-MM-DD")
			getDuytInfoFun()
		}
	}
	
	onLoad((opt)=>{
		const {dutyId:_dutyId}=opt
		dutyId.value = _dutyId
		getDuytInfoFun()
		getDutyClockListFun()
		nextTick(()=>{
			uni.$emit('autoShowPushScreenAd')
		})
	})
	
	onShow(()=>{
		getDuytInfoFun(false)
		nextTick(()=>{
			setTimeout(()=>{
				uni.$emit('getUserInfo',true)
			},300)
		})
	})
</script>

<style lang="less">
	.text_ellipsis {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.duty_clock_box{
		.header{
			height: 300rpx;
			position: relative;
			background-color: v-bind(primary_light_color);
			.orther_info{
				position: absolute;
				width: 100%;
				display: flex;
				justify-content: space-between;
				.item{
					display: flex;
					align-items: center;
					padding: 0 20rpx;
					font-size: 24rpx;
					color: #FFFFFF;
				}
				.item:nth-child(2){
					width: 20%;
					justify-content: flex-end;
				}
				.item:nth-child(1){
					position: relative;
					width: 80%;
					height: 55rpx;
					.count{
						background-color: rgba(118,168,169,.5);
						position: absolute;
						left: 64rpx;
						min-width:15%;
						padding: 5rpx 20rpx 5rpx 25rpx;
						z-index: 1;
						border-radius: 0 20rpx 20rpx 0;
					}
				}
			}
			.duty_info_box{
				position: absolute;
				width: 100%;
				height: 100%;
				z-index: 2;
				box-sizing: border-box;
				padding: 70rpx 20rpx;
				.user{
					width: 100%;
					display: flex;
					align-items: center;
					.name{
						margin-left: 10rpx;
						width: 40%;
						font-size: 30rpx;
						color: v-bind(primary_text_color);
					}
				}
			}
			.duty_info{
				position: absolute;
				top: 55%;
				transform: translate(0,-15%);
				left: 20rpx;
				width: 50%;
				color: v-bind(primary_text_color);
				display: flex;
				font-size: 30rpx;
				.week{
					font-size: 50rpx;
					margin-bottom: -30rpx;
					position: relative;
					top: -23rpx;
					color: #FFFFFF;
					margin: 0 4rpx;
				}
			}
			.duty_clock_count{
				position: absolute;
				width: 60%;
				color: v-bind(primary_text_color);
				display: flex;
				font-size: 30rpx;
				top: 66%;
				left: 20rpx;
				z-index: 2;
				.count{
					margin: 0 4px;
					font-size: 50rpx;
					margin-bottom: -30rpx;
					position: relative;
					top: -18rpx;
				}
				.no{
					color: v-bind(primary_text_hot_color);
				}
				.yes{
					color: #FFFFFF;
				}
			}
			.duty_clock_count_2{
				position: absolute;
				width: 60%;
				color: v-bind(primary_text_color);
				display: flex;
				font-size: 30rpx;
				top: 80%;
				left: 20rpx;
				z-index: 2;
				.count{
					color: #FFFFFF;
				}
			}
		}
		.content{
			.duty_calendar{
				padding: 0 20rpx;
				.duty_clock_btn_box{
					margin-top: 20rpx;
				}
			}
			background-image: linear-gradient(to top, rgba(97,214,213,0),rgba(97,214,213,1));
			height: 100vh;
		}
		.edit{
			position: absolute;
			padding: 5rpx;
			right: 0;
			top: 0;
			background-color: v-bind(primary_light_color);
			color: #FFFFFF;
			border-radius: 0 12rpx 0 12rpx;
			display: flex;
			align-items: center;
		}
		.clock_info_item{
			display: flex;
			align-items: center;
			color: v-bind(primary_text_color);
			margin-top: 10rpx;
			.title{
				width: 50rpx;
			}
		}
		.clock_info_item_info{
			display: flex;
			margin-top: 10rpx;
			.title{
				width: 50rpx;
			}
			.info{
				flex: 1;
				padding-top: 4rpx;
				color: v-bind(primary_text_color);
				word-break: break-all;
			}
			.imgs{
				display: grid;
				grid-template-columns: repeat(3,1fr);
				gap:30rpx;
			}
		}
	}
	.upload_tip{
		font-size: 28rpx;
		color: v-bind(primary_text_color);
		margin: 10rpx 0;
	}
	.proof{
		display: grid;
		grid-template-columns: repeat(3,1fr);
		align-items: center;
		gap: 30rpx;
		width: 94%;
		.img{
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			.close_btn{
				position: absolute;
				top: -16rpx;
				right: -15rpx;
			}
		}
	}
</style>
